package com.self.ry.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Copyright: Copyright (c) 2019
 *
 * @Description: 该类的功能描述
 * @Version: v1.0.0
 * @Author ruyi
 * @Date 2019/4/19 10:28
 */
public final class IPUtil {
    private static final Logger logger = LoggerFactory.getLogger(IPUtil.class);

    public static void main(String[] args) {
        try {
            System.out.println("get LocalHost Address : " + getLocalHostLANAddress().getHostAddress());
        } catch (Exception e) {

        }
    }


    public static String getLocalIP() {
        String ip = null;
        try {
            InetAddress address = getLocalHostLANAddress();
            if (address != null) {
                ip = address.getHostAddress();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return ip;
    }


    /**
     * 正确的IP拿法，即优先拿site-local地址
     * 站点本地地址
     * @return
     * @throws UnknownHostException
     */
    private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }
}
